package service

import (
	"fmt"
	"wangchunguang_blog/model"
)

func CountSubscriber() (int, error) {

	var count int
	err := db.Model(&model.Subscriber{}).Where("verify_state = ? and subscribe_state = ?", true, true).Count(&count).Error
	if err != nil {
		fmt.Println("出现查询错误:", err)
		return 0, err
	}
	return count, err
}

// 通过邮箱获取订阅信息
func GetSubscriberBySigneture(key string) (*model.Subscriber, error) {

	var subscriber model.Subscriber
	err := db.Find(&subscriber, "email =?").Error
	if err != nil {
		fmt.Println("出现查询错误:", err)
		return nil, err
	}
	return &subscriber, err
}

// 修改订阅信息
func UpdateSubscriber(subscriber *model.Subscriber) error {
	return db.Model(subscriber).Updates(map[string]interface{}{
		"verify_state":    subscriber.VerifyState,
		"subscribe_state": subscriber.SubscribeState,
		"out_time":        subscriber.OutTime,
		"signature":       subscriber.Signature,
		"secret_key":      subscriber.SecretKey,
	}).Error
}

// 新增订阅
func InsertSubscriber(subscriber *model.Subscriber) error {
	return db.FirstOrCreate(subscriber, "email =?", subscriber.Email).Error
}

// 通过id获取订阅
func GetSubscriBySignature(key string) (*model.Subscriber, error) {
	var sub model.Subscriber
	e := db.Find(&sub, "signature =?", key).Error
	if err != nil {
		fmt.Println("出现查询错误:", err)
		return nil, err
	}
	return &sub, e
}

func ListSubscriber(incalid bool) ([]*model.Subscriber, error) {
	var sub []*model.Subscriber
	DB := db.Model(&model.Subscriber{})
	if incalid {
		DB.Where("verify_state = ? and subscribe_state = ?", true, true)
	}
	err := DB.Find(&sub).Error
	if err != nil {
		fmt.Println("出现查询错误:", err)
		return nil, err
	}
	return sub, err

}

// 通过id查询订阅信息
func GetSubscriberById(id uint) (*model.Subscriber, error) {
	var sub model.Subscriber
	e := db.First(&sub, id).Error
	return &sub, e
}
